package com.haitrinh.NativeMediaPicker
{
	import com.haitrinh.NativeMediaPicker.NativeMediaPickerEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.StatusEvent;
	import flash.external.ExtensionContext;
	
	public class NativeMediaPicker extends EventDispatcher
	{
		protected var extensionContext:ExtensionContext;
		
		private static const EXTENSION_ID : String = "com.haitrinh.NativeMediaPicker.NativeMediaPicker";
		private static const PLAY_COMMAND : String = "play";
		private static const PAUSE_COMMAND : String = "pause";
		
		public function NativeMediaPicker(target:IEventDispatcher=null)
		{
			super(target);
			extensionContext = ExtensionContext.createExtensionContext( EXTENSION_ID, null);
		}
		
		/**
		 * Open iOS media picker 
		 **/
		
		public function showMediaPicker():void{
			extensionContext.addEventListener( StatusEvent.STATUS, onStatusEvent);
			extensionContext.call( "showMediaPicker");
		}
		
		
		/**
		 * Play and Pause Song 
		 **/
		
		public function playSong(play:Boolean):void{
			extensionContext.addEventListener( StatusEvent.STATUS, onStatusEvent);
			if(play == true)
				extensionContext.call( "playSong",PLAY_COMMAND);
			else
				extensionContext.call( "playSong",PAUSE_COMMAND);
		}
		
		/**
		 * Seek Song
		 **/
		
		public function seek(playbackTime:int):void{
			var playback:String = String(playbackTime);
			extensionContext.addEventListener( StatusEvent.STATUS, onStatusEvent);
			extensionContext.call( "seek",playback);
		}
		
		/**
		 * @private
		 * Handle iOS media result. 
		 * When picker media finished an result event will be dispatched.
		 * Event will contain the result information.
		 *
		 */		
		private function onStatusEvent( event : StatusEvent ) : void
		{

			dispatchEvent( new NativeMediaPickerEvent(event.code, event.level ));
			
		}
		
		
		/**
		 * Clean up
		 */	
		public function dispose():void {
			extensionContext.removeEventListener( StatusEvent.STATUS, onStatusEvent );
			extensionContext.dispose();
		}
	}
}